/**
 *  created by wenxiao.li
 *  Date: 2021/6/8
 *  Time: 9:52
 *  Version: 1.0
 *  For: basic form
 */
import {
  ref, unref, onUnmounted, set, watch, isRef,
} from '@vue/composition-api';

export function useForm(props) {
  // 表单默认props
  const baseProps = {
    model: {},
    schemas: [],
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
    layout: 'horizontal',
    disabled: false,
  };
  // 合并默认和设置的props
  const formProps = ref({
    ...baseProps,
    ...props,
    schemas: unref(props.schemas),
  });

  // 表单配置项可以监听
  if (isRef(props.schemas)) {
    watch(props.schemas, (value) => {
      formProps.value.schemas = value.filter((schema) => !schema.isHidden);
    });
  }

  function initForm(instance) {
    if (unref(formRef) === instance) return;
    formRef.value = instance;
    setDefaultValue();
  }

  onUnmounted(() => {
    formRef.value = null;
  });

  const formRef = ref(null);

  function getForm() {
    return unref(formRef);
  }

  const setDefaultValue = () => {
    const schemas = unref(props.schemas);
    const keys = Object.keys(formProps.value.model);
    // model没有初始化的设置默认值
    schemas.forEach((schema) => {
      if (!keys.includes(schema.field)) {
        set(formProps.value.model, schema.field, schema.defaultValue);
      }
    });
  };

  const methods = {
    clearValidate: (name) => {
      getForm().clearValidate(name);
    },
    resetFields: () => {
      getForm().resetFields();
    },
    removeSchemaByFiled: (field) => {
      formProps.value.schemas = formProps.value.schemas.filter((item) => item.field === field || field.includes(item.field));
    },
    getFieldValue: (field) => getForm().model[field],
    getFieldsValue: () => getForm().model,
    setFieldValue: (field, value) => {
      getForm().model[field] = value;
    },
    setFieldsValue: (values) => {
      getForm().model = values;
    },
    appendSchemaByField: (schema) => {
      formProps.value.schemas.push(schema);
    },
    validate: async () => getForm().validate(),
    submit: async () => {
      // 提交表单
      try {
        await getForm().validate();
        return handleSubmitForm();
      } catch (e) {
        throw new Error(e);
      }
    },
  };

  // 处理要提交的表单数据
  function handleSubmitForm() {
    // 所有表单项
    const keys = Object.keys(getForm().model);
    const { model } = getForm();
    unref(unref(formProps).schemas).forEach((schema) => {
      if (keys.includes(schema.field)) {
        // 处理range picker
        if (schema.component === 'RangePicker') {
          const rangeValue = model[schema.field];
          // rangeValue 通过fieldMap 映射
          if (rangeValue && rangeValue.length) {
            rangeValue.forEach((value, index) => {
              if (schema.fieldMap) {
                model[schema.fieldMap[index]] = new Date(value).getTime();
              }
            });
          }
        }
        if (schema.component === 'Cascader') {
          const value = model[schema.field];
          if (schema.fieldMap) {
            schema.fieldMap.forEach((_, index) => {
              model[_] = value[index];
            });
          }
        }
      }
    });
    return model;
  }

  return {
    formProps,
    initForm,
    methods,
  };
}
